# -*- coding: utf-8 -*-
# @Time    : 2024/10/29 15:46
# @Author  : CHNJX
# @File    : extensions.py
# @Desc    : 扩展池

from flask import Flask, current_app
from apscheduler.schedulers.background import BackgroundScheduler
from pytz import timezone
import atexit
import logging

# 创建全局调度器但不立即启动它
scheduler = BackgroundScheduler(timezone=timezone('Asia/Shanghai'))


def init_extensions(app: Flask):
    """Initialize Flask extensions."""
    # 检查调度器状态，避免重复启动
    if not scheduler.running:
        scheduler.start()
        app.logger.info("Background scheduler started")
        
        # 注册应用关闭时的清理函数
        @app.teardown_appcontext
        def shutdown_scheduler(exception=None):
            """确保在应用上下文结束时关闭调度器"""
            try:
                if scheduler.running:
                    scheduler.shutdown(wait=False)
                    app.logger.info("Background scheduler shutdown")
            except Exception as e:
                app.logger.error(f"关闭调度器时出错: {str(e)}")
        
        # 使用atexit确保在Python解释器退出时调度器被关闭
        def cleanup_scheduler():
            try:
                if scheduler.running:
                    scheduler.shutdown(wait=False)
                    logging.info("Background scheduler shutdown on exit")
            except Exception as e:
                logging.error(f"退出时关闭调度器出错: {str(e)}")
        
        atexit.register(cleanup_scheduler)
